/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.gnucash.client.mvc;

import app.gnucash.client.AppEvents;
import app.gnucash.client.MainEntryPoint;
import app.gnucash.client.thesisServiceAsync;
import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.google.gwt.user.client.rpc.AsyncCallback;


/**
 *
 * @author cc
 */
public class AppController extends Controller {

    private AppView appView;
    private thesisServiceAsync service;

    @Override
    public void initialize() {
        appView = new AppView(this);
    }

    public AppController() {
        registerEventTypes(AppEvents.Init);
        registerEventTypes(AppEvents.Login);
        registerEventTypes(AppEvents.Error);
    }

    public void handleEvent(AppEvent event) {
        EventType type = event.getType();
        if (type == AppEvents.Init) {
            onInit(event);
        } else if (type == AppEvents.Login) {
            onLogin(event);
        } else if (type == AppEvents.Error) {
            onError(event);
        }
    }

    protected void onError(AppEvent ae) {
        System.out.println("error: " + ae.<Object>getData());
    }

    private void onInit(AppEvent event) {
        forwardToView(appView, event);
//        service = (thesisServiceAsync) Registry.get(MainEntryPoint.SERVICE);
//        service.getthesisTitles(new AsyncCallback<Folder>() {
//
//            public void onFailure(Throwable caught) {
//                Dispatcher.forwardEvent((EventType) Registry.get("AppInitError"), caught);
//            }
//
//            public void onSuccess(Folder result) {
//                Dispatcher.forwardEvent((EventType) Registry.get("AppInitSuccess"), result);
//            }
//        });
    }

    private void onLogin(final AppEvent event) {
        // if session's user is null, then forward to login
        // else forword to init
        service = (thesisServiceAsync) Registry.get(MainEntryPoint.SERVICE);
        service.getSessionUser(new AsyncCallback<String>() {

            public void onFailure(Throwable caught) {
                Dispatcher.forwardEvent((EventType) Registry.get("AppInitError"), caught);
            }

            public void onSuccess(String result) {
                if (!(result.equals(""))) {
                    AppEvent env = new AppEvent(AppEvents.Init);
                    env.setData("user", result);
                    Dispatcher.forwardEvent(env);
                } else {
                    forwardToView(appView, event);
                }
            }
        });
    }
}
